package cn.edu.baiyunu.myapplication.ui.screens.home.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.Help
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.data.model.Transaction
import cn.edu.baiyunu.myapplication.ui.components.GlassmorphismCard
import cn.edu.baiyunu.myapplication.ui.utils.formatDateTime
import cn.edu.baiyunu.myapplication.ui.utils.getIconByName
import java.text.NumberFormat
import java.util.Locale

/**
 * 最近交易列表组件
 */
@Composable
fun RecentTransactionsList(
    transactions: List<Transaction>,
    categoryMap: Map<String, Category>,
    onViewAllClick: () -> Unit,
    onTransactionClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    GlassmorphismCard(
        modifier = modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.padding(25.dp)
        ) {
            // 标题栏
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "近期交易",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
                
                Text(
                    text = "查看全部",
                    fontSize = 14.sp,
                    color = Color.White.copy(alpha = 0.8f),
                    modifier = Modifier.clickable { 
                        println("首页 - 点击了'查看全部'按钮")
                        onViewAllClick() 
                    }
                )
            }
            
            Spacer(modifier = Modifier.height(20.dp))
            
            // 交易列表
            if (transactions.isEmpty()) {
                // 空状态
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 20.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无交易记录",
                        color = Color.White.copy(alpha = 0.7f)
                    )
                }
            } else {
                // 为LazyColumn设置固定高度，避免嵌套滚动冲突
                LazyColumn(
                    modifier = Modifier.height(200.dp),
                    verticalArrangement = Arrangement.spacedBy(15.dp)
                ) {
                    items(transactions) { transaction ->
                        TransactionListItem(
                            transaction = transaction,
                            category = categoryMap[transaction.categoryId],
                            onClick = { onTransactionClick(transaction.id) }
                        )
                    }
                }
            }
        }
    }
}

/**
 * 单个交易列表项
 */
@Composable
private fun TransactionListItem(
    transaction: Transaction,
    category: Category?,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 分类图标
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(Color.White.copy(alpha = 0.15f)),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = category?.let { getIconByName(it.icon) } ?: Icons.AutoMirrored.Rounded.Help,
                contentDescription = category?.name ?: "未知分类",
                tint = Color.White
            )
        }
        
        // 交易详情
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 15.dp)
        ) {
            Text(
                text = category?.name ?: "未知分类",
                fontSize = 16.sp,
                color = Color.White,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            
            if (transaction.note.isNotBlank()) {
                Text(
                    text = transaction.note,
                    fontSize = 12.sp,
                    color = Color.White.copy(alpha = 0.7f),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            } else {
                Text(
                    text = formatDateTime(transaction.date),
                    fontSize = 12.sp,
                    color = Color.White.copy(alpha = 0.7f)
                )
            }
        }
        
        // 交易金额
        val isExpense = transaction.type == "expense"
        val prefix = if (isExpense) "-" else "+"
        val color = if (isExpense) Color(0xFFFF5E62) else Color(0xFF26DE81)
        
        Text(
            text = "$prefix${formatCurrency(transaction.amount)}",
            fontWeight = FontWeight.Bold,
            color = color
        )
    }
}

/**
 * 格式化金额为货币格式
 */
private fun formatCurrency(amount: Double): String {
    val format = NumberFormat.getCurrencyInstance(Locale.CHINA)
    return format.format(amount).replace("¥", "￥")
} 